package com.hq.ims.data.service;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hq.ims.data.dao.CompanyMapper;
import com.hq.ims.data.entity.*;
import com.hq.ims.data.entityenum.*;
import com.hq.ims.data.event.CompanyEvent;
import com.hq.ims.data.utils.LocalConstant;
import com.hq.ims.data.utils.ObjectComparatorUtil;
import com.hq.ims.data.vo.*;
import com.hq.mybatis.base.BaseService;
import com.hq.mybatis.base.page.RequestPage;
import com.hq.mybatis.base.page.ReturnPage;
import com.hq.utils.exception.CommonException;
import com.hq.utils.util.*;
import lombok.NonNull;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Nonnull;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * jiang bai ping
 *
 * @Email 526666031@qq.com
 * @Detail 公司表服务实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BaseCompanyService extends BaseService<CompanyMapper, Company> {

    @Resource
    private BaseCompanyCheckService baseCompanyCheckService;
    @Resource
    private BaseCompanyEmployeeService baseCompanyEmployeeService;
    @Resource
    private BaseCompanyDepartmentService baseCompanyDepartmentService;
    @Resource
    private RedisTemplate<String, Company> redisTemplateCompany;
    @Resource
    private BaseCompanyServiceAreaService baseCompanyServiceAreaService;
    @Resource
    private BaseCompanyServiceTypeHistoryService baseCompanyServiceTypeHistoryService;
    @Resource
    private BaseCompanyServiceTypeService baseCompanyServiceTypeService;
    @Resource
    private BaseCompanyServiceAreaHistoryService baseCompanyServiceAreaHistoryService;
    @Resource
    private BaseCompanyAptitudeService baseCompanyAptitudeService;
    @Value("${userAttribute.companyDefaultAvatar}")
    private String initCompanyAvatar;
    @Resource
    private BaseCompanyAptitudeHistoryService baseCompanyAptitudeHistoryService;
    @Resource
    private BaseCompanyChangeHistoryService baseCompanyChangeHistoryService;
    @Resource
    private BaseCompanyRuleHistoryService baseCompanyRuleHistoryService;
    @Resource
    private BaseFileRecordService baseFileRecordService;
    @Resource
    private BaseBusiInfoService baseBusiInfoService;
    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private BaseDictService baseDictService;
    @Resource
    private BaseBusiChangeService baseBusiChangeService;
    @Resource
    private BasePermissionMapAuthorityDepartmentService basePermissionMapAuthorityDepartmentService;
    @Resource
    private BasePermissionMapRoleUserService basePermissionMapRoleUserService;
    @Resource
    private BasePermissionMapAuthorityRoleService basePermissionMapAuthorityRoleService;
    @Resource
    private BasePermissionAuthorityService basePermissionAuthorityService;
    @Resource
    private BasePermissionMapAuthorityMenuService basePermissionMapAuthorityMenuService;
    @Resource
    private BasePermissionRoleService basePermissionRoleService;
    @Resource
    private BasePermissionGroupService basePermissionGroupService;
    @Resource
    private BaseCompanyDepartmentEmployeeService baseCompanyDepartmentEmployeeService;

    /**
     * 判断是否存在该公司
     *
     * @param companyName 公司名称
     * @param companyId   公司id
     */
    public boolean isExistCompanyName(
            @Nonnull String companyName,
            String companyId
    ) {
        return this.lambdaQuery()
                .eq(Company::getCompanyName, companyName)
                .ne(StringUtils.isNotEmpty(companyId), Company::getCompanyId, companyId)
                .count() > 0;
    }

    /**
     * 根据产业标获取公司
     */
    public List<Company> getByCompanyServiceTypeId(
            String companyServiceTypeId
    ) {
        List<CompanyServiceType> companyServiceList = baseCompanyServiceTypeService.lambdaQuery()
                .select(CompanyServiceType::getCompanyId)
                .eq(StringUtils.isNotEmpty(companyServiceTypeId), CompanyServiceType::getServiceTypeId, companyServiceTypeId)
                .list();

        if (ListUtils.isNotExistsEle(companyServiceList)) {
            return ListUtils.newEmptyList();
        }

        List<String> compayIdList = companyServiceList.stream()
                .map(CompanyServiceType::getCompanyId)
                .distinct()
                .collect(Collectors.toList());

        if (ListUtils.isExistsEle(compayIdList)) {
            return lambdaQuery().in(Company::getCompanyId, compayIdList).orderByDesc(Company::getCreateDateTime).list();
        }

        return ListUtils.newEmptyList();
    }

    /**
     * 获取公司树和公司下的用户
     *
     * @param companyId 公司ID
     */
    public List<CompanyMapstruct.CompanyTreeVo> getCompanyTreeVoByCompanyId(
            @NonNull String companyId,
            @NonNull boolean isShowCompanyDepartment,
            @NonNull boolean isIncludeOneself,
            @NonNull boolean isInclusionChildren
    ) {
        Company company = this.getById(companyId);
        if (company == null) {
            return ListUtils.newEmptyList();
        }

        List<Company> dataList = this.getAllChildrenCompanyList(companyId, isIncludeOneself);
        //获取所有公司
        List<CompanyMapstruct.CompanyTreeVo> companyTreeVoList = CompanyMapstruct.INSTANCE.toCompanyTreeVoList(dataList);
        if (ListUtils.isNotExistsEle(companyTreeVoList)) {
            return ListUtils.newEmptyList();
        }

        //转换为树
        companyTreeVoList = ParentChildrenClassificationUtils.classificationToTree(
                companyTreeVoList,
                d -> d.getCompanyId(),
                d -> d.getParentId(),
                (d, c) -> d.setChildrenCompanyList(c),
                d -> d.setParentId(StringUtils.FH_ZERO),
                company.getParentId()
        );

        if (ListUtils.isNotExistsEle(companyTreeVoList)) {
            return ListUtils.newEmptyList();
        }

        if (!isInclusionChildren) {
            //包含下级公司
            companyTreeVoList.forEach(d -> {
                d.setChildrenCompanyList(null);
            });
        }

        if (!isIncludeOneself) {
            //不包含自身
            companyTreeVoList = companyTreeVoList.stream().filter(d -> d.getCompanyId().equals(companyId)).collect(Collectors.toList());
        }

        //填充用户数量和部门数据
        this.recursionFillTreeEmployeeCountAndDepartmentData(companyTreeVoList, isShowCompanyDepartment);
        return companyTreeVoList;
    }

    private void recursionFillTreeEmployeeCountAndDepartmentData(
            List<CompanyMapstruct.CompanyTreeVo> tree,
            boolean isShowDepartment
    ) {
        //填充用户数量和部门数据
        tree.forEach(companyTreeVo -> {

            Long companyEmployeeCount = baseCompanyEmployeeService.getCompanyEmployeeCountByCompanyId(companyTreeVo.getCompanyId(), false);
            companyTreeVo.setEmployeeCount(companyEmployeeCount);

            if (isShowDepartment) {
                List<CompanyDepartment> companyDepartmentList = baseCompanyDepartmentService.getByCompanyId(companyTreeVo.getCompanyId());
                List<CompanyDepartmentMapstruct.SimpleCompanyDepartmentVo> departmentVoList = CompanyDepartmentMapstruct.INSTANCE.toSimpleCompanyDepartmentVoList(companyDepartmentList);
                companyTreeVo.setChildrenDepartmentList(departmentVoList);
            }
            List<CompanyMapstruct.CompanyTreeVo> childrenCompanyList = companyTreeVo.getChildrenCompanyList();
            if (ListUtils.isExistsEle(childrenCompanyList)) {
                this.recursionFillTreeEmployeeCountAndDepartmentData(childrenCompanyList, isShowDepartment);
            }
        });
    }

    /**
     * 添加子公司,根据参数完成公司的认证和公司树的创建
     */
    @Transactional(rollbackFor = Exception.class)
    public Company addPlatformCompany(
            @NonNull String parentId,
            @NonNull String companyName
    ) {
        boolean isExistCompanyName = this.isExistCompanyName(companyName, StringUtils.EMPTY);
        BooleanUtils.isTrueThrow(isExistCompanyName, "已存在同名公司,请修改后继续添加");

        EnumCompanyLevel companyLevel = EnumCompanyLevel.values()[0];
        String companyId = SeqUtils.generateUuidNoHorizontalLine();
        String rootId = companyId;
        if (!StringUtils.FH_ZERO.equals(parentId)) {
            Company parentCompany = this.lambdaQuery()
                    .eq(Company::getCompanyId, parentId)
                    .last(LocalConstant.LIMIT_1)
                    .one();
            rootId = parentCompany.getRootId();
            ObjectUtils.isNullThrow(parentCompany, "父公司不存在");
            companyLevel = EnumCompanyLevel.getByCode(parentCompany.getCompanyLevel().getNextCode());
            ObjectUtils.isNullThrow(companyLevel, "当前已经到最底级了不能再添加子级公司了");
        }

        //获取公司的信息,添加子公司
        Company company = new Company();
        company.setCompanyName(companyName);
        company.setCompanyLevel(companyLevel);
        company.setCity(StringUtils.EMPTY);
        company.setStatus(EnumCompanyStatus.Normal);
        company.setContactMobile(StringUtils.EMPTY);
        company.setDistrict(StringUtils.EMPTY);
        company.setBusinessLicenseImages(StringUtils.EMPTY);
        company.setContactPerson(StringUtils.EMPTY);
        company.setLogoUrl(initCompanyAvatar);
        company.setProvince(StringUtils.EMPTY);
        company.setStreet(StringUtils.EMPTY);
        company.setParentId(parentId);
        company.setCompanyDivideIntoRuleValue(BigDecimal.ZERO);
        company.setRootId(rootId);
        boolean bl = company.insert();

        BooleanUtils.isFalseThrow(bl, "添加公司失败,请联系管理员");
        return company;
    }

    /**
     * 添加用户端公司
     *
     * @param vo
     */
    @Transactional(rollbackFor = Exception.class)
    public Company addUserCompany(User user, CompanyMapstruct.UserRegisterNewCompanySaveVo vo) {
        String parentId = StringUtils.ifEmptyDefault(vo.getParentCompanyId(), LocalConstant.PLATFORM_COMPANY_ID_LIST.get(0));
        boolean isExistCompanyName = this.isExistCompanyName(vo.getCompanyName(), StringUtils.EMPTY);
        BooleanUtils.isTrueThrow(isExistCompanyName, "已存在同名公司,请修改后继续添加");
        Dict companyCardTypeDict = baseDictService.getById(vo.getCompanyCardTypeId());
        ObjectUtils.isNullThrow(companyCardTypeDict, "证件类型不能为空");

        EnumCompanyLevel companyLevel = EnumCompanyLevel.values()[0];
        String companyId = SeqUtils.generateUuidNoHorizontalLine();
        String rootId = companyId;
        if (!StringUtils.FH_ZERO.equals(parentId)) {
            Company parentCompany = this.lambdaQuery()
                    .eq(Company::getCompanyId, parentId)
                    .last(LocalConstant.LIMIT_1)
                    .one();
            rootId = parentCompany.getRootId();
            ObjectUtils.isNullThrow(parentCompany, "父公司不存在");
            companyLevel = EnumCompanyLevel.getByCode(parentCompany.getCompanyLevel().getNextCode());
            ObjectUtils.isNullThrow(companyLevel, "当前已经到最底级了不能再添加子级公司了");
        }

        //获取公司的信息,添加子公司
        Company company = new Company();
        company.setCompanyName(vo.getCompanyName());
        company.setCompanyLevel(companyLevel);
        company.setCity(StringUtils.EMPTY);
        company.setStatus(EnumCompanyStatus.Normal);
        company.setAuditStatus(EnumAuditStatus.UnderReview);
        company.setContactMobile(StringUtils.EMPTY);
        company.setDistrict(StringUtils.EMPTY);
        company.setBusinessLicenseImages(StringUtils.EMPTY);
        company.setContactPerson(StringUtils.EMPTY);
        company.setLogoUrl(initCompanyAvatar);
        company.setProvince(StringUtils.EMPTY);
        company.setStreet(StringUtils.EMPTY);
        company.setParentId(parentId);
        company.setCompanyDivideIntoRuleValue(vo.getCompanyDivideIntoRuleValue());
        company.setRootId(rootId);
        company.setCompanyCardTypeName(companyCardTypeDict.getName());
        company.setCompanyCardTypeId(companyCardTypeDict.getDictId());
        company.setCompanyCardNumber(vo.getCompanyCardNumber());
        company.setBusinessRange(vo.getBusinessRange());
        company.setCompanyAddress(vo.getCompanyAddress());
        company.setCreateUserId(user.getUserId());
        company.setCreateUserName(user.getRealName());
//        company.setBaseStatus(EnumAuditStatus.UnderReview);
//        company.setRuleStatus(EnumAuditStatus.UnderReview);

        if (StringUtils.isNotEmpty(parentId)) {
            Company parentCompany = this.getById(parentId);
            company.setParentName(parentCompany.getCompanyName());
        }

        boolean bl = company.insert();

        //补check
        CompanyCheck check = JsonUtils.convertObject(company, CompanyCheck.class);
        check.setCompanyId(company.getCompanyId());
        check.setCheckType(EnumCheckType.FirstCheck);
        check.setCompanyUpdateType(EnumCompanyUpdateType.AllUpdate);
        baseCompanyCheckService.save(check);

        //保存证件文件
        baseFileRecordService.saveFile(vo.getCompanyCardFile(), CompanyCheck.class, check.getId(), LocalConstant.FILE_COMPANY_CARD, true);
        //保存分成规则文件
        if (vo.getCompanyDivideIntoRuleFile() != null) {
            baseFileRecordService.saveFile(vo.getCompanyCardFile(), CompanyCheck.class, check.getId(), LocalConstant.FILE_COMPANY_DIVIDE_INTO_RULE, true);
        }

        //保存资质
        Map<String, List<String>> companyAptitudeGroupMap = vo.getCompanyAptitudeList().stream()
                .map(d -> d.getCompanyAptitudeName())
                .collect(Collectors.groupingBy(d -> d));
        boolean isExistCompanyAptitudeRepeatEle = companyAptitudeGroupMap.values().stream().filter(d -> d.size() > 1).count() > 0;
        BooleanUtils.isTrueThrow(isExistCompanyAptitudeRepeatEle, "存在相同的资质名称");


        for (CompanyAptitudeMapstruct.SaveVo saveVo : vo.getCompanyAptitudeList()) {
            CompanyAptitudeMapstruct.SaveVo build = new CompanyAptitudeMapstruct.SaveVo();
            build.setCompanyId(company.getCompanyId());
            build.setCheckId(check.getId());
            build.setCompanyAptitudeName(saveVo.getCompanyAptitudeName());
            build.setLv(saveVo.getLv());
            build.setValidEndDate(saveVo.getValidEndDate());
            build.setFileVo(saveVo.getFileVo());
            baseCompanyAptitudeHistoryService.addData(build);
        }

        //保存服务范围
        for (CompanyServiceAreaMapstruct.SaveVo saveVo : vo.getCompanyServiceAreaList()) {
            CompanyServiceAreaMapstruct.SaveVo build = new CompanyServiceAreaMapstruct.SaveVo();
            build.setCompanyId(company.getCompanyId());
            build.setCheckId(check.getId());
            build.setProvinceCode(saveVo.getProvinceCode());
            build.setCityCode(saveVo.getCityCode());
            baseCompanyServiceAreaHistoryService.addData(build);
        }

        //保存产业标记
        Map<String, List<String>> companyServiceTypeGroupMap = vo.getCompanyServiceTypeList().stream()
                .map(d -> d.getServiceTypeId())
                .collect(Collectors.groupingBy(d -> d));
        boolean isExistCompanyServiceTypeRepeatEle = companyServiceTypeGroupMap.values().stream().filter(d -> d.size() > 1).count() > 0;
        BooleanUtils.isTrueThrow(isExistCompanyServiceTypeRepeatEle, "存在相同的产业标记");

        for (CompanyServiceTypeMapstruct.SaveVo saveVo : vo.getCompanyServiceTypeList()) {
            CompanyServiceTypeMapstruct.SaveVo build = new CompanyServiceTypeMapstruct.SaveVo();
            build.setCompanyId(company.getCompanyId());
            build.setCheckId(check.getId());
            build.setServiceTypeId(saveVo.getServiceTypeId());
            baseCompanyServiceTypeHistoryService.addData(build);
        }

        BooleanUtils.isFalseThrow(bl, "添加公司失败,请联系管理员");

        return company;
    }

    /**
     * 更新公司状态
     *
     * @param companyId 公司ID
     * @param status    状态
     */
    public Boolean updateCompanyStatus(
            String companyId,
            EnumAccountStatus status
    ) {
        return this.lambdaUpdate().eq(Company::getCompanyId, companyId).set(Company::getStatus, status).update();
    }

    /**
     * 获取数据范围公司sql
     */
    public String getDataRangeSql(String companyId, boolean isFindCurAndBelow) {

        List<Company> companyList = new ArrayList<>(0);
        if (isFindCurAndBelow) {
            companyList = this.getAllChildrenCompanyList(companyId, true);
        } else {
            companyList.add(this.getRedisCompanyById(companyId));
        }

        List<String> companyIds = companyList.stream().map(d -> "'" + d.getCompanyId() + "'").collect(Collectors.toList());
        if (ListUtils.isNotExistsEle(companyIds)) {
            companyIds.add("''");
        }
        return String.join(StringUtils.FH_COMMA, companyIds);
    }

    //--------------------------------------------- 以下是查询 ---------------------------------------------
    //--------------------------------------------- 获取子级 ---------------------------------------------

    //获取子级公司
    public List<Company> getChildrenCompanyList(
            @NonNull String parentId
    ) {
        List<Company> redisAllCompanyList = this.getRedisAllCompanyList();
        List<Company> companyList = redisAllCompanyList.stream().filter(d -> d.getParentId().equals(parentId)).collect(Collectors.toList());
        return companyList;
    }

    public List<Company> getChildrenCompanyList(
            @NonNull String parentId,
            boolean isIncludeOneself
    ) {
        List<Company> redisAllCompanyList = this.getRedisAllCompanyList();
        List<Company> companyList = redisAllCompanyList.stream().filter(d -> d.getParentId().equals(parentId)).collect(Collectors.toList());
        if (isIncludeOneself) {
            companyList.addAll(redisAllCompanyList.stream().filter(d -> d.getCompanyId().equals(parentId)).collect(Collectors.toList()));
        }
        return companyList;
    }

    /**
     * 获取当前公司及以下公司id
     *
     * @param companyId 公司id
     */
    public List<String> getChildrenIdList(String companyId, boolean isIncludeOneself) {
        List<Company> companyList = this.getAllChildrenCompanyList(companyId, isIncludeOneself);
        if (ListUtils.isNotExistsEle(companyList)) {
            return ListUtils.newEmptyList();
        }
        return companyList.stream().map(Company::getCompanyId).distinct().collect(Collectors.toList());
    }

    public List<Company> getAllChildrenCompanyList(
            @NonNull String companyId
    ) {
        return this.getAllChildrenCompanyList(companyId, false);
    }

    public List<Company> getAllChildrenCompanyList(
            @NonNull String companyId,
            boolean isIncludeOneself
    ) {
        return this.getAllChildrenCompanyList(companyId, isIncludeOneself, null);
    }

    /**
     * 查询所有公司
     *
     * @param companyId              公司ID
     * @param isIncludeOneself       是否包含自身
     * @param allowChoseCompanyLevel 子级必须在这个级别中
     */
    public List<Company> getAllChildrenCompanyList(
            @NonNull String companyId,
            boolean isIncludeOneself,
            List<EnumCompanyLevel> allowChoseCompanyLevel
    ) {
        Map<String, Company> redisAllCompanyMap = this.getRedisAllCompanyMap();
        Company curCompany = redisAllCompanyMap.get(companyId);
        ObjectUtils.isNullThrow(curCompany, "该公司不存在,请联系管理员");

        Set<Company> saveContainerSet = new HashSet<>();
        this.recursionFindAllChildrenCompany(companyId, new ArrayList<>(redisAllCompanyMap.values()), saveContainerSet);

        List<Company> finalCompanyList = new ArrayList<>(saveContainerSet);
        //需要查询的公司级别
        if (ListUtils.isExistsEle(allowChoseCompanyLevel)) {
            finalCompanyList = finalCompanyList.stream().filter(d -> allowChoseCompanyLevel.contains(d.getCompanyLevel())).collect(Collectors.toList());
        }
        if (isIncludeOneself) {
            finalCompanyList.add(curCompany);
        }
        finalCompanyList = finalCompanyList.stream()
                .sorted(Comparator.comparing(Company::getCompanyLevel)
                        .thenComparing(Company::getCreateDateTime))
                .collect(Collectors.toList());
        return finalCompanyList;
    }


    /**
     * 向下查找
     *
     * @param parentId         父ID
     * @param totalDataList    需要查找的数据
     * @param saveContainerSet 保存的容器
     */
    public Set<Company> recursionFindAllChildrenCompany(
            String parentId,
            List<Company> totalDataList,
            Set<Company> saveContainerSet
    ) {
        //获取子数据
        List<Company> childrenCompanyList = totalDataList.stream().filter(d -> d.getParentId().equals(parentId)).collect(Collectors.toList());
        if (ListUtils.isNotExistsEle(childrenCompanyList)) {
            return saveContainerSet;
        }
        //继续查找子数据
        for (Company company : childrenCompanyList) {
            saveContainerSet.add(company);
            this.recursionFindAllChildrenCompany(company.getCompanyId(), totalDataList, saveContainerSet);
        }
        return saveContainerSet;
    }

    //--------------------------------------------- 获取父级 ---------------------------------------------

    //获取子级公司
    public Company getParentCompany(
            @NonNull String companyId
    ) {
        Map<String, Company> redisAllCompanyMap = this.getRedisAllCompanyMap();
        Company company = redisAllCompanyMap.get(companyId);
        ObjectUtils.isNullThrow(company, "公司不存在");
        Company parentCompany = redisAllCompanyMap.get(company.getParentId());
        return parentCompany;
    }

    public List<String> getAllParentCompanyIdList(String companyId) {
        List<Company> allParentCompanyList = this.getAllParentCompanyList(companyId);
        List<String> allCompanyIdList = allParentCompanyList.stream().map(Company::getCompanyId).collect(Collectors.toList());
        return allCompanyIdList;
    }

    public List<Company> getAllParentCompanyList(String companyId) {
        return this.getAllParentCompanyList(Arrays.asList(companyId), false);
    }

    public List<Company> getAllParentCompanyList(
            List<String> companyIdList,
            boolean isIncludeOneself
    ) {
        return this.getAllParentCompanyList(companyIdList, isIncludeOneself, null);
    }

    /**
     * 向上查找
     *
     * @param companyIdList                公司ID信合
     * @param isIncludeOneself             是否所括自已,true在返回的信合中包括自已,false只有父公司
     * @param assignParentCompanyLevelList 指定父公司级别
     */
    public List<Company> getAllParentCompanyList(
            List<String> companyIdList,
            boolean isIncludeOneself,
            List<EnumCompanyLevel> assignParentCompanyLevelList
    ) {
        Map<String, Company> redisAllCompanyMap = this.getRedisAllCompanyMap();
        //递归查找所有父级
        Set<Company> saveContainerSet = new HashSet<>();
        for (String companyId : companyIdList) {
            this.recursionFindAllParentCompany(companyId, redisAllCompanyMap, saveContainerSet);
        }
        List<Company> finalList = new ArrayList<>();
        if (ListUtils.isExistsEle(assignParentCompanyLevelList)) {
            for (Company company : saveContainerSet) {
                if (assignParentCompanyLevelList.contains(company.getCompanyLevel())) {
                    finalList.add(company);
                }
            }
        } else {
            for (Company company : saveContainerSet) {
                finalList.add(company);
            }
        }

        if (!isIncludeOneself) {
            //因为默认是包含查询出来的,如果不需要自身就要去掉
            finalList = finalList.stream().filter(d -> !companyIdList.contains(d.getCompanyId())).collect(Collectors.toList());
        }
        return finalList;
    }

    /**
     * 递归查找所有父ID
     *
     * @param curCompanyId     当前公司ID
     * @param totalDataMap     需要查找的总数据
     * @param saveContainerSet 保存容器
     */
    public Set<Company> recursionFindAllParentCompany(
            String curCompanyId,
            Map<String, Company> totalDataMap,
            Set<Company> saveContainerSet
    ) {
        Company curCompany = totalDataMap.get(curCompanyId);
        if (curCompany == null) {
            return saveContainerSet;
        }
        saveContainerSet.add(curCompany);
        if (StringUtils.FH_ZERO.equals(curCompany.getParentId())) {
            return saveContainerSet;
        }
        Company parentCompany = totalDataMap.get(curCompany.getParentId());
        return this.recursionFindAllParentCompany(parentCompany.getCompanyId(), totalDataMap, saveContainerSet);
    }

    /**
     * 获取用户所有公司名称
     */
    public List<String> getUserAllCompanyNameListByUserId(
            @NonNull String userId,
            Boolean isPartTimeJob
    ) {
        List<String> userAllCompanyIdList = baseCompanyEmployeeService.getUserAllCompanyIdListByUserId(userId, isPartTimeJob);
        List<Company> redisAllCompanyList = this.getRedisAllCompanyList();
        List<String> userAllCompanyNameList = redisAllCompanyList.stream()
                .filter(d -> userAllCompanyIdList.contains(d.getCompanyId()))
                .map(Company::getCompanyName)
                .distinct()
                .collect(Collectors.toList());
        return userAllCompanyNameList;
    }


    //--------------------------------------------- 获取redis数据 ---------------------------------------------

    /**
     * 从redis中获取公司信息
     */
    public List<Company> getRedisAllCompanyList() {
        Long size = redisTemplateCompany.opsForList().size(LocalConstant.REDIS_LIST_KEY_COMPANY);
        List<Company> redisCompanyList = redisTemplateCompany.opsForList().range(LocalConstant.REDIS_LIST_KEY_COMPANY, 0, size);
        if (ListUtils.isNotExistsEle(redisCompanyList)) {
            //查库
            synchronized (this) {
                size = redisTemplateCompany.opsForList().size(LocalConstant.REDIS_LIST_KEY_COMPANY);
                redisCompanyList = redisTemplateCompany.opsForList().range(LocalConstant.REDIS_LIST_KEY_COMPANY, 0, size);
                if (ListUtils.isNotExistsEle(redisCompanyList)) {
                    List<Company> dataCompanyList = this.lambdaQuery().eq(Company::getStatus, EnumCompanyStatus.Normal).orderByAsc(Company::getCreateDateTime).list();
                    redisTemplateCompany.opsForList().rightPushAll(LocalConstant.REDIS_LIST_KEY_COMPANY, dataCompanyList);
                    redisCompanyList = dataCompanyList;
                }
            }
        }
        return redisCompanyList;
    }

    /**
     * 从redis中获取公司信息
     */
    public Map<String, Company> getRedisAllCompanyMap() {
        List<Company> redisAllCompanyList = this.getRedisAllCompanyList();
        return redisAllCompanyList.stream().collect(Collectors.toMap(Company::getCompanyId, d -> d));
    }

//    /**
//     * 从redis中获取公司信息
//     */
//    public Map<String, List<Company>> getRedisAllCompanyGroupByParentId() {
//        List<Company> redisAllCompanyList = this.getRedisAllCompanyList();
//        return redisAllCompanyList.stream().collect(Collectors.groupingBy(Company::getParentId));
//    }

    /**
     * 更新redis所有公司
     */
    public void updateRedisAllCompany() {
        redisTemplateCompany.delete(LocalConstant.REDIS_LIST_KEY_COMPANY);
        this.getRedisAllCompanyList();
    }

//    /**
//     * 根据ID找查公司
//     */
//    public List<Company> getRedisCompanyByInId(List<String> companyIdList) {
//        List<Company> redisAllCompany = this.getRedisAllCompanyList();
//        if (ListUtils.isNotExistsEle(redisAllCompany)) {
//            return new ArrayList<>(0);
//        }
//        return redisAllCompany.stream().filter(company -> companyIdList.contains(company.getCompanyId())).collect(Collectors.toList());
//    }

    /**
     * 根据ID查找公司
     *
     * @param companyId 公司ID
     */
    public Company getRedisCompanyById(String companyId) {
        List<Company> redisAllCompany = this.getRedisAllCompanyList();
        if (ListUtils.isNotExistsEle(redisAllCompany)) {
            return null;
        }
        List<Company> companyList = redisAllCompany.stream().filter(company -> company.getCompanyId().equals(companyId)).collect(Collectors.toList());
        if (ListUtils.isNotExistsEle(companyList)) {
            return null;
        }
        return companyList.get(0);
    }

    public ReturnPage getCompanyPage(RequestPage page, CompanyMapstruct.PageSearchVo searchVo) {

        List<String> companyIds = new ArrayList<>();

        //产业标记
        if (StringUtils.isNotEmpty(searchVo.getServiceTypeName())) {
            List<CompanyServiceType> serviceTypes = baseCompanyServiceTypeService.lambdaQuery()
                    .like(StringUtils.isNotEmpty(searchVo.getServiceTypeName()), CompanyServiceType::getServiceTypeName, searchVo.getServiceTypeName())
                    .list();
            if (ListUtils.isExistsEle(serviceTypes)) {
                List<String> strings = serviceTypes.stream().map(CompanyServiceType::getCompanyId).collect(Collectors.toList());
                companyIds.addAll(strings);
            } else {
                return new ReturnPage();
            }
        }

        if (StringUtils.isNotEmpty(searchVo.getServiceAreaName())) {
            //服务地区
            List<CompanyServiceArea> serviceAreas = baseCompanyServiceAreaService.lambdaQuery()
                    .like(StringUtils.isNotEmpty(searchVo.getServiceAreaName()), CompanyServiceArea::getProvinceName, searchVo.getServiceAreaName())
                    .list();

            if (ListUtils.isExistsEle(serviceAreas)) {
                List<String> strings = serviceAreas.stream().map(CompanyServiceArea::getCompanyId).collect(Collectors.toList());
                companyIds.addAll(strings);
            } else {
                return new ReturnPage();
            }
        }

        if (StringUtils.isNotEmpty(searchVo.getParentId())) {
            List<Company> childrenCompanyList = this.getAllChildrenCompanyList(searchVo.getParentId(), true);
            List<String> strings = childrenCompanyList.stream().map(Company::getCompanyId).collect(Collectors.toList());
            companyIds.addAll(strings);
        }

        List<String> list = companyIds.stream().distinct().collect(Collectors.toList());

        RequestPage requestPage = this.lambdaQuery()
                .like(StringUtils.isNotEmpty(searchVo.getCompanyName()), Company::getCompanyName, searchVo.getCompanyName())
                .eq(StringUtils.isNotEmpty(searchVo.getParentId()), Company::getParentId, searchVo.getParentId())
                .like(StringUtils.isNotEmpty(searchVo.getParentName()), Company::getParentName, searchVo.getParentName())
                .in(ListUtils.isExistsEle(list), Company::getCompanyId, list)
                .orderByDesc(Company::getCreateDateTime)
                .page(page);

        if (ListUtils.isNotExistsEle(requestPage.getRecords())) {
            return requestPage.getReturnPage();
        }

        List<CompanyMapstruct.CompanyVo> vos = JsonUtils.convertListObject(requestPage.getRecords(), CompanyMapstruct.CompanyVo.class);

        for (CompanyMapstruct.CompanyVo vo : vos) {
            //组合产业标记
            List<CompanyServiceType> types = baseCompanyServiceTypeService.lambdaQuery().eq(CompanyServiceType::getCompanyId, vo.getCompanyId()).list();
            vo.setServiceType(types);

            //组合服务地区
            List<CompanyServiceArea> areas = baseCompanyServiceAreaService.lambdaQuery().eq(CompanyServiceArea::getCompanyId, vo.getCompanyId()).list();
            vo.setServiceArea(areas);

            vo.setParentName(null);

            if (StringUtils.isNotEmpty(vo.getParentId())) {
                Company parentCompany = this.getById(vo.getParentId());
                if (parentCompany != null) {
                    vo.setParentName(parentCompany.getCompanyName());
                }
            }
        }

        requestPage.setRecords(vos);

        return requestPage.getReturnPage();
    }

    /**
     * 查询企业信息详情
     *
     * @param company
     * @return
     */
    public CompanyMapstruct.CompanyVo getCompanyDetail(Company company) {

        if (StringUtils.isEmpty(company.getCompanyId())) {
            throw CommonException.build("需要查询的数据为空");
        }

        Company one = this.lambdaQuery().eq(Company::getCompanyId, company.getCompanyId()).one();

        CompanyMapstruct.CompanyVo vo = JsonUtils.convertObject(one, CompanyMapstruct.CompanyVo.class);

        if (one != null) {

            //组合产业标记
            List<CompanyServiceType> types = baseCompanyServiceTypeService.lambdaQuery().eq(CompanyServiceType::getCompanyId, vo.getCompanyId()).list();
            vo.setServiceType(types);

            //组合服务地区
            List<CompanyServiceArea> areas = baseCompanyServiceAreaService.lambdaQuery().eq(CompanyServiceArea::getCompanyId, vo.getCompanyId()).list();
            vo.setServiceArea(areas);

            List<FileRecord> fileRecords = baseFileRecordService.lambdaQuery()
                    .eq(FileRecord::getFileMark, LocalConstant.FILE_COMPANY_CARD)
                    .eq(FileRecord::getOwnTableDataId, one.getCompanyId())
                    .list();

            List<AppFileMapstruct.FileVo> fileVos = baseFileRecordService.changeFileRecordToFileVo(fileRecords);
            vo.setCompanyIdFiles(fileVos);

            List<CompanyAptitude> aptitudes = baseCompanyAptitudeService.lambdaQuery().eq(CompanyAptitude::getCompanyId, one.getCompanyId()).list();

            if (ListUtils.isExistsEle(aptitudes)) {
                List<CompanyAptitudeMapstruct.CompanyAptitudeVo> aptitudeVos = JsonUtils.convertListObject(aptitudes, CompanyAptitudeMapstruct.CompanyAptitudeVo.class);
                for (CompanyAptitudeMapstruct.CompanyAptitudeVo aptitudeVo : aptitudeVos) {
                    List<FileRecord> file = baseFileRecordService.getFile(aptitudeVo.getCompanyAptitudeId(), LocalConstant.FILE_COMPANY_APTITUDE);
                    List<AppFileMapstruct.FileVo> aptitudeFiles = baseFileRecordService.changeFileRecordToFileVo(file);
                    aptitudeVo.setFiles(aptitudeFiles);
                }
                vo.setCompanyAptitudeFiles(aptitudeVos);
            }

            List<FileRecord> ruleFiles = baseFileRecordService.getFile(company.getCompanyId(), LocalConstant.FILE_COMPANY_DIVIDE_INTO_RULE);
            List<AppFileMapstruct.FileVo> ruleFileVos = baseFileRecordService.changeFileRecordToFileVo(ruleFiles);
            vo.setCompanyRuleFiles(ruleFileVos);

            List<BusiInfo> busiInfoList = baseBusiInfoService.getCompanyBusiInfoList(company.getCompanyId(), EnumBusinessTypeStatus.ExternalStatement);
            vo.setBusiInfoList(busiInfoList);

            if (vo.getAuditStatus() == EnumAuditStatus.NotPass) {
                CompanyCheck check = baseCompanyCheckService.getLastCheckByCompanyId(vo.getCompanyId());
                vo.setCompanyOffReason(check.getRejectReason());
            }

        }

        return vo;
    }

    public boolean checkCompanyInfo(List<CompanyCheckMapstruct.CompanyCheckVo> checks) {

        if (ListUtils.isNotExistsEle(checks)) {
            throw CommonException.build("审核参数为空");
        }

        for (CompanyCheckMapstruct.CompanyCheckVo checkParam : checks) {

            CompanyCheck check = baseCompanyCheckService.getById(checkParam.getId());

            if (check == null) {
                throw CommonException.build("审核失败，审核数据不存在!");
            }

            Company company = this.lambdaQuery().eq(Company::getCompanyId, check.getCompanyId()).one();
            if (company == null) {
                throw CommonException.build("审核失败，企业信息不存在!");
            }

            if (check.getAuditStatus() == EnumAuditStatus.Pass) {
                return true;
            }

            //审核状态
            check.setAuditStatus(checkParam.getAuditStatus());

            this.lambdaUpdate().eq(Company::getCompanyId, check.getCompanyId())
                    .set(Company::getAuditStatus, checkParam.getAuditStatus())
                    .update();

            //通过
            if (checkParam.getAuditStatus() == EnumAuditStatus.Pass) {
                this.lambdaUpdate().eq(Company::getCompanyId, check.getCompanyId())
                        .set(Company::getCompanyName, check.getCompanyName())
                        .set(Company::getCompanyCardNumber, check.getCompanyCardNumber())
                        .set(Company::getCompanyCardTypeName, check.getCompanyCardTypeName())
                        .set(Company::getCompanyAddress, check.getCompanyAddress())
                        .set(Company::getBusinessRange, check.getBusinessRange())
                        .set(Company::getProvince, check.getProvince())
                        .set(Company::getCity, check.getCity())
                        .set(Company::getDistrict, check.getDistrict())
                        .set(Company::getStreet, check.getStreet())
                        .set(Company::getBusinessLicenseImages, check.getBusinessLicenseImages())
                        .set(Company::getParentId, check.getParentId())
                        .set(Company::getParentName, check.getParentName())
                        .set(Company::getStatus, EnumCompanyStatus.Normal)
                        .set(Company::getCompanyDivideIntoRuleValue, check.getCompanyDivideIntoRuleValue())
                        .update();

                //服务地区
                baseCompanyServiceAreaService.lambdaUpdate().eq(CompanyServiceArea::getCompanyId, company.getCompanyId()).remove();
                List<CompanyServiceAreaHistory> areaList = baseCompanyServiceAreaHistoryService.getCompanyAllServiceAreaList(check.getId(), EnumDataType.After.getCode());
                List<CompanyServiceArea> areas = JsonUtils.convertListObject(areaList, CompanyServiceArea.class);
                for (CompanyServiceArea area : areas) {
                    area.setCompanyId(company.getCompanyId());
                }
                baseCompanyServiceAreaService.saveBatch(areas);

                //产业标记
                baseCompanyServiceTypeService.lambdaUpdate().eq(CompanyServiceType::getCompanyId, company.getCompanyId()).remove();
                List<CompanyServiceTypeHistory> typeList = baseCompanyServiceTypeHistoryService.getCompanyAllServiceTypeList(check.getId(), EnumDataType.After.getCode());
                List<CompanyServiceType> types = JsonUtils.convertListObject(typeList, CompanyServiceType.class);
                for (CompanyServiceType type : types) {
                    type.setCompanyServiceTypeId(null);
                    type.setCompanyId(company.getCompanyId());
                }
                baseCompanyServiceTypeService.saveBatch(types);

                //保存企业的证件照片
                baseFileRecordService.delFile(company.getCompanyId(), LocalConstant.FILE_COMPANY_CARD);
                List<FileRecord> file = baseFileRecordService.getFile(check.getId(), LocalConstant.FILE_COMPANY_CARD);
                List<AppFileMapstruct.FileVo> fileVos = baseFileRecordService.changeFileRecordToFileVo(file);
                baseFileRecordService.saveFile(fileVos, Company.class, company.getCompanyId(), LocalConstant.FILE_COMPANY_CARD, true);

                //保存企业的资质
                List<CompanyAptitudeHistory> aptitudeHistories = baseCompanyAptitudeHistoryService.getCompanyAllAptitudeList(check.getId(), EnumDataType.After.getCode());

                if (ListUtils.isExistsEle(aptitudeHistories)) {

                    //删除旧的资质
                    baseCompanyAptitudeService.lambdaUpdate().eq(CompanyAptitude::getCompanyId, company.getCompanyId()).remove();

                    List<CompanyAptitude> aptitudes = JsonUtils.convertListObject(aptitudeHistories, CompanyAptitude.class);
                    for (CompanyAptitude aptitude : aptitudes) {

                        List<FileRecord> aptitudesFile = baseFileRecordService.getFile(aptitude.getCompanyAptitudeId(), LocalConstant.FILE_COMPANY_APTITUDE);

                        aptitude.setCompanyAptitudeId(null);
                        aptitude.setCompanyId(company.getCompanyId());

                        baseCompanyAptitudeService.save(aptitude);

                        List<AppFileMapstruct.FileVo> afterFiles = baseFileRecordService.changeFileRecordToFileVo(aptitudesFile);
                        baseFileRecordService.saveFile(afterFiles, CompanyAptitude.class, aptitude.getCompanyAptitudeId(), LocalConstant.FILE_COMPANY_APTITUDE, true);
                    }
                }

                //关联收益规则说明
                List<FileRecord> oldRuleFile = baseFileRecordService.getFile(check.getId(), LocalConstant.FILE_COMPANY_DIVIDE_INTO_RULE);
                List<AppFileMapstruct.FileVo> vos = baseFileRecordService.changeFileRecordToFileVo(oldRuleFile);
                baseFileRecordService.saveFile(vos, Company.class, company.getCompanyId(), LocalConstant.FILE_COMPANY_DIVIDE_INTO_RULE, true);
            } else {
                check.setRejectReason(checkParam.getRejectReason());
            }

            baseCompanyCheckService.updateById(check);

            //发送事件
            Company lastCompanyData = this.getById(company.getCompanyId());
            if (checkParam.getAuditStatus() == EnumAuditStatus.Pass) {
                applicationContext.publishEvent(new CompanyEvent(this, lastCompanyData, CompanyEvent.PLATFORM_AUDIT_PASS_EVENT));
            } else {
                applicationContext.publishEvent(new CompanyEvent(this, lastCompanyData, CompanyEvent.PLATFORM_AUDIT_NOT_PASS_EVENT));
            }
        }

        return true;
    }

    /**
     * 修改企业信息
     *
     * @param companyVo
     * @return
     */
    public boolean updCompanyInfo(CompanyMapstruct.CompanyVo companyVo) {

        if (companyVo.getCompanyDivideIntoRuleValue() != null) {
            //重置收益值格式与数据库保持一致否则 10 比 10.00下面对比不一致
            companyVo.setCompanyDivideIntoRuleValue(BigDecimalUtil.divide(companyVo.getCompanyDivideIntoRuleValue(), BigDecimal.ONE, 2));
        }

//        SpringBootValidateUtils.validate(companyVo, VdEdit.class);

        Company company = this.getById(companyVo.getCompanyId());
        if (company.getAuditStatus() == EnumAuditStatus.UnderReview) {
            throw CommonException.build("数据正在审核中，禁止修改");
        }

        //判断企业名称
        Long count = this.lambdaQuery().ne(Company::getCompanyId, company.getCompanyId())
                .eq(Company::getCompanyName, companyVo.getCompanyName()).count();
        if (count > 0) {
            throw CommonException.build("修改失败，公司名称已经存在");
        }

        List<BusiChange> changes = new ArrayList<>();

        if (!baseCompanyCheckService.isFirstCheck(companyVo.getCompanyId())) {
            //判断字段修改并记录
            Map<String, String> compare = ObjectComparatorUtil.compare(company, companyVo);
            if (!compare.isEmpty()) {
                for (Map.Entry<String, String> entry : compare.entrySet()) {
                    BusiChange change = new BusiChange();
                    change.setChangeWay(EnumChangeWay.UserChange);
                    change.setBusiInfoId(company.getCompanyId());
                    change.setChangeTime(LocalDateTime.now());
                    change.setChangeContent(entry.getKey());
                    change.setChangeBefore(entry.getValue().split("_")[0]);
                    change.setChangeAfter(entry.getValue().split("_")[1]);
                    changes.add(change);
                }

                //证件照片
                List<FileRecord> file = baseFileRecordService.getFile(company.getCompanyId(), LocalConstant.FILE_COMPANY_CARD);
                List<String> oldIdFiles = file.stream().map(FileRecord::getFileId).collect(Collectors.toList());
                List<String> newIdFiles = companyVo.getCompanyIdFiles().stream().map(AppFileMapstruct.FileVo::getFileId).collect(Collectors.toList());
                boolean b = new HashSet<>(oldIdFiles).containsAll(newIdFiles);
                if (!b) {
                    BusiChange change = new BusiChange();
                    change.setChangeWay(EnumChangeWay.UserChange);
                    change.setBusiInfoId(company.getCompanyId());
                    change.setChangeTime(LocalDateTime.now());
                    change.setChangeContent("证件照片");
                    change.setChangeBefore("");
                    change.setChangeAfter("证件照片有更新");
                    changes.add(change);
                }

                //企业资质
                List<CompanyAptitudeMapstruct.CompanyAptitudeVo> oldAptitudeInfo = baseCompanyAptitudeService.getAptitudeInfoByCompanyId(company.getCompanyId());
                List<String> oldAptId = oldAptitudeInfo.stream().map(CompanyAptitude::getCompanyAptitudeId).collect(Collectors.toList());
                List<String> newAptId = companyVo.getCompanyAptitudeFiles().stream().map(CompanyAptitude::getCompanyAptitudeId).collect(Collectors.toList());

                if (oldAptId.size() != newAptId.size() || !new HashSet<>(oldAptId).containsAll(newAptId)) {
                    BusiChange change = new BusiChange();
                    change.setChangeWay(EnumChangeWay.UserChange);
                    change.setBusiInfoId(company.getCompanyId());
                    change.setChangeTime(LocalDateTime.now());
                    change.setChangeContent("企业资质");
                    change.setChangeBefore("");
                    change.setChangeAfter("企业资质有更新");
                    changes.add(change);
                }

                //收益规则文件
                List<FileRecord> oldRuleFiles = baseFileRecordService.getFile(company.getCompanyId(), LocalConstant.FILE_COMPANY_DIVIDE_INTO_RULE);
                List<String> oldRuleIds = oldRuleFiles.stream().map(FileRecord::getFileId).collect(Collectors.toList());

                List<String> newRuleFileIds = companyVo.getCompanyRuleFiles().stream().map(AppFileMapstruct.FileVo::getFileId).collect(Collectors.toList());
                if (oldRuleIds.size() != newRuleFileIds.size() || !new HashSet<>(oldRuleIds).containsAll(newRuleFileIds)) {
                    BusiChange change = new BusiChange();
                    change.setChangeWay(EnumChangeWay.UserChange);
                    change.setBusiInfoId(company.getCompanyId());
                    change.setChangeTime(LocalDateTime.now());
                    change.setChangeContent("收益规则文件");
                    change.setChangeBefore("");
                    change.setChangeAfter("收益规则文件有更新");
                    changes.add(change);
                }

                //服务地区
                List<CompanyServiceArea> areas = baseCompanyServiceAreaService.lambdaQuery().eq(CompanyServiceArea::getCompanyId, company.getCompanyId()).list();
                List<String> oldArea = areas.stream().map(CompanyServiceArea::getProvinceName).collect(Collectors.toList());

                List<String> newArea = companyVo.getServiceArea().stream().map(CompanyServiceArea::getProvinceName).collect(Collectors.toList());
                if (oldArea.size() != newArea.size() || !new HashSet<>(oldArea).containsAll(newArea)) {
                    BusiChange change = new BusiChange();
                    change.setChangeWay(EnumChangeWay.UserChange);
                    change.setBusiInfoId(company.getCompanyId());
                    change.setChangeTime(LocalDateTime.now());
                    change.setChangeContent("服务地区");
                    change.setChangeBefore(oldArea.toString());
                    change.setChangeAfter(newArea.toString());
                    changes.add(change);
                }

                //产业标记
                List<CompanyServiceType> oldType = baseCompanyServiceTypeService.lambdaQuery().eq(CompanyServiceType::getCompanyId, company.getCompanyId()).list();
                List<String> oldTypeNames = oldType.stream().map(CompanyServiceType::getServiceTypeName).collect(Collectors.toList());

                List<String> newTypeNames = companyVo.getServiceType().stream().map(CompanyServiceType::getServiceTypeName).collect(Collectors.toList());

                if (oldTypeNames.size() != newTypeNames.size() || !new HashSet<>(oldTypeNames).containsAll(newTypeNames)) {
                    BusiChange change = new BusiChange();
                    change.setChangeWay(EnumChangeWay.UserChange);
                    change.setBusiInfoId(company.getCompanyId());
                    change.setChangeTime(LocalDateTime.now());
                    change.setChangeContent("产业标记");
                    change.setChangeBefore(oldTypeNames.toString());
                    change.setChangeAfter(newTypeNames.toString());
                    changes.add(change);
                }
            }
        }

        if (ListUtils.isExistsEle(changes)) {
            baseBusiChangeService.saveBatch(changes);
        }

        //创建check
        CompanyCheck check = JsonUtils.convertObject(companyVo, CompanyCheck.class);
        check.setCheckType(EnumCheckType.ChangeCheck);

        //判断初次审核
        List<CompanyCheck> list = baseCompanyCheckService.lambdaQuery().eq(CompanyCheck::getCompanyId, company.getCompanyId()).eq(CompanyCheck::getAuditStatus, EnumAuditStatus.Pass).list();
        if (ListUtils.isNotExistsEle(list)) {
            check.setCheckType(EnumCheckType.FirstCheck);
        }

        check.setAuditStatus(EnumAuditStatus.UnderReview);
        check.setCompanyUpdateType(companyVo.getCompanyUpdateType());
        baseCompanyCheckService.save(check);

        this.lambdaUpdate().eq(Company::getCompanyId, company.getCompanyId())
                .set(Company::getAuditStatus, EnumAuditStatus.UnderReview)
                .update();

        //全部信息修改
        this.updateCompanyBaseInfo(companyVo, check);

        return true;
    }

    public void updateCompanyBaseInfo(CompanyMapstruct.CompanyVo companyVo, CompanyCheck check) {

        Company company = this.getById(companyVo.getCompanyId());

        //创建history （证件，资质，服务地区，产业标记

        //服务地区（之前）
        List<CompanyServiceArea> areas = baseCompanyServiceAreaService.lambdaQuery().eq(CompanyServiceArea::getCompanyId, check.getCompanyId()).list();
        List<CompanyServiceAreaHistory> areaHistories = JsonUtils.convertListObject(areas, CompanyServiceAreaHistory.class);
        for (CompanyServiceAreaHistory areaHistory : areaHistories) {
            areaHistory.setDataType(EnumDataType.Before);
            areaHistory.setCompanyServiceAreaId(areaHistory.getCompanyServiceAreaId());
            areaHistory.setCompanyCheckId(check.getId());
        }

        baseCompanyServiceAreaHistoryService.saveBatch(areaHistories);

        //服务地区（之后）
        List<CompanyServiceAreaHistory> areaHistoryList = JsonUtils.convertListObject(companyVo.getServiceArea(), CompanyServiceAreaHistory.class);
        for (CompanyServiceAreaHistory areaHistory : areaHistoryList) {
            areaHistory.setDataType(EnumDataType.After);
            areaHistory.setCompanyServiceAreaId(areaHistory.getCompanyServiceAreaId());
            areaHistory.setCompanyCheckId(check.getId());
        }
        baseCompanyServiceAreaHistoryService.saveBatch(areaHistoryList);

        //产业标记（之前）
        List<CompanyServiceType> types = baseCompanyServiceTypeService.lambdaQuery().eq(CompanyServiceType::getCompanyId, check.getCompanyId()).list();
        List<CompanyServiceTypeHistory> typeHistories = JsonUtils.convertListObject(types, CompanyServiceTypeHistory.class);
        for (CompanyServiceTypeHistory typeHistory : typeHistories) {
            typeHistory.setDataType(EnumDataType.Before);
            typeHistory.setCompanyServiceTypeId(typeHistory.getCompanyServiceTypeId());
            typeHistory.setCompanyCheckId(check.getId());
        }

        baseCompanyServiceTypeHistoryService.saveBatch(typeHistories);

        //产业标记（之后）
        List<CompanyServiceTypeHistory> serviceTypeHistories = JsonUtils.convertListObject(companyVo.getServiceType(), CompanyServiceTypeHistory.class);
        for (CompanyServiceTypeHistory typeHistory : serviceTypeHistories) {
            typeHistory.setDataType(EnumDataType.After);
            typeHistory.setCompanyServiceTypeId(typeHistory.getCompanyServiceTypeId());
            typeHistory.setCompanyCheckId(check.getId());
        }
        baseCompanyServiceTypeHistoryService.saveBatch(serviceTypeHistories);

        //证件
        baseFileRecordService.saveFile(JsonUtils.convertListObject(companyVo.getCompanyIdFiles(), AppFileMapstruct.FileVo.class), Company.class, check.getId(), LocalConstant.FILE_COMPANY_CARD, true);

        List<CompanyAptitudeHistory> histories = new ArrayList<>();

        //资质(之后)
        for (CompanyAptitudeMapstruct.CompanyAptitudeVo companyAptitudeFile : companyVo.getCompanyAptitudeFiles()) {
            CompanyAptitudeHistory history = JsonUtils.convertObject(companyAptitudeFile, CompanyAptitudeHistory.class);
            history.setCompanyAptitudeId(null);
            history.setCompanyCheckId(check.getId());
            history.setDateType(EnumDataType.After);
            baseCompanyAptitudeHistoryService.save(history);

            //保存check的资质文件
            baseFileRecordService.saveFile(companyAptitudeFile.getFiles(), CompanyAptitudeHistory.class, history.getCompanyAptitudeId(), LocalConstant.FILE_COMPANY_APTITUDE, true);
        }
        //资质（之前）
        List<CompanyAptitude> aptitudes = baseCompanyAptitudeService.lambdaQuery().eq(CompanyAptitude::getCompanyId, companyVo.getCompanyId()).list();
        for (CompanyAptitude aptitude : aptitudes) {
            CompanyAptitudeHistory history = JsonUtils.convertObject(aptitude, CompanyAptitudeHistory.class);
            history.setCompanyAptitudeId(null);
            history.setCompanyCheckId(check.getId());
            history.setDateType(EnumDataType.Before);
            histories.add(history);
        }

        baseCompanyAptitudeHistoryService.saveBatch(histories);

        //规则
        CompanyRuleHistory ruleHistory = new CompanyRuleHistory();
        ruleHistory.setCompanyId(companyVo.getCompanyId());
        ruleHistory.setCompanyName(companyVo.getCompanyName());
        ruleHistory.setCompanyCheckId(check.getId());
        ruleHistory.setCompanyDivideIntoRuleValue(companyVo.getCompanyDivideIntoRuleValue());
        ruleHistory.setAuditStatus(EnumAuditStatus.UnderReview);
        ruleHistory.setDataType(EnumDataType.After);
        baseCompanyRuleHistoryService.save(ruleHistory);

        //收益规则（之前）
        CompanyRuleHistory beforeHistory = new CompanyRuleHistory();
        beforeHistory.setCompanyId(companyVo.getCompanyId());
        beforeHistory.setCompanyName(companyVo.getCompanyName());
        beforeHistory.setCompanyCheckId(check.getId());
        beforeHistory.setAuditStatus(EnumAuditStatus.Pass);
        beforeHistory.setDataType(EnumDataType.Before);
        beforeHistory.setCompanyDivideIntoRuleValue(company.getCompanyDivideIntoRuleValue());

        baseCompanyRuleHistoryService.save(beforeHistory);

        baseFileRecordService.saveFile(companyVo.getCompanyRuleFiles(), CompanyCheck.class, check.getId(), LocalConstant.FILE_COMPANY_DIVIDE_INTO_RULE, true);
    }

    /**
     * 查询企业审核列表
     *
     * @param page
     * @param searchVo
     * @return
     */
    public ReturnPage checkCompanyPage(RequestPage page, CompanyMapstruct.PageSearchVo searchVo) {

        List<String> companyList = new ArrayList<>();

        if (StringUtils.isNotEmpty(searchVo.getParentId())) {
            List<Company> childrenCompanyList = this.getAllChildrenCompanyList(searchVo.getParentId(), true);
            companyList = childrenCompanyList.stream().map(Company::getCompanyId).collect(Collectors.toList());
        }

        RequestPage requestPage = baseCompanyCheckService.lambdaQuery()
                .eq(searchVo.getCheckType() != null, CompanyCheck::getCheckType, searchVo.getCheckType())
                .like(StringUtils.isNotEmpty(searchVo.getCompanyName()), CompanyCheck::getCompanyName, searchVo.getCompanyName())
                .like(StringUtils.isNotEmpty(searchVo.getCompanyCardNumber()), CompanyCheck::getCompanyCardNumber, searchVo.getCompanyCardNumber())
                .like(StringUtils.isNotEmpty(searchVo.getCompanyCardTypeName()), CompanyCheck::getCompanyCardTypeName, searchVo.getCompanyCardTypeName())
                .between(searchVo.getStartDate() != null, CompanyCheck::getCreateDateTime, searchVo.getStartDate(), searchVo.getEndDate())
                .and(qr -> qr.eq(CompanyCheck::getCompanyUpdateType, EnumCompanyUpdateType.BaseInfo).or().eq(CompanyCheck::getCompanyUpdateType, EnumCompanyUpdateType.AllUpdate))
                .in(ListUtils.isExistsEle(companyList), CompanyCheck::getCompanyId, companyList)
                .orderByDesc(CompanyCheck::getCreateDateTime)
                .page(page);

        if (ListUtils.isExistsEle(requestPage.getRecords())) {

            List<CompanyCheckMapstruct.CompanyCheckVo> checkVos = JsonUtils.convertListObject(requestPage.getRecords(), CompanyCheckMapstruct.CompanyCheckVo.class);

            for (CompanyCheckMapstruct.CompanyCheckVo record : checkVos) {

                List<FileRecord> file = baseFileRecordService.getFile(record.getId(), LocalConstant.FILE_COMPANY_CARD);

                record.setCompanyIdFiles(baseFileRecordService.changeFileRecordToFileVo(file));

                //组合产业标记
                List<CompanyServiceTypeHistory> types = baseCompanyServiceTypeHistoryService.getCompanyAllServiceTypeList(record.getId(), EnumDataType.After.getCode());
                record.setServiceType(types);

                //组合服务地区
                List<CompanyServiceAreaHistory> areas = baseCompanyServiceAreaHistoryService.getCompanyAllServiceAreaList(record.getId(), EnumDataType.After.getCode());
                record.setServiceArea(areas);

                //上级组织
                record.setParentName(null);

                if (StringUtils.isNotEmpty(record.getParentId())) {
                    Company parentCompany = this.getById(record.getParentId());
                    if (parentCompany != null) {
                        record.setParentName(parentCompany.getCompanyName());
                    }
                }
            }

            requestPage.setRecords(checkVos);
        }

        return requestPage.getReturnPage();
    }

    /**
     * 查看企业审核详情
     *
     * @param check
     * @return
     */
    public CompanyCheckMapstruct.CompanyCheckVo checkCompanyDetail(CompanyCheck check) {

        if (StringUtils.isEmpty(check.getId())) {
            throw CommonException.build("查询参数为空");
        }

        CompanyCheck companyCheck = baseCompanyCheckService.getById(check.getId());
        if (companyCheck == null) {
            throw CommonException.build("查询企业审核数据为空");
        }

        CompanyCheckMapstruct.CompanyCheckVo checkVo = JsonUtils.convertObject(companyCheck, CompanyCheckMapstruct.CompanyCheckVo.class);

        //组合证件照片
        List<FileRecord> companyCard = baseFileRecordService.getFile(checkVo.getId(), LocalConstant.FILE_COMPANY_CARD);
        List<AppFileMapstruct.FileVo> fileVos = baseFileRecordService.changeFileRecordToFileVo(companyCard);
        checkVo.setCompanyIdFiles(fileVos);
        //查询服务地区
        List<CompanyServiceAreaHistory> serviceAreaHistories = baseCompanyServiceAreaHistoryService.getCompanyAllServiceAreaList(checkVo.getId(), EnumDataType.After.getCode());
        checkVo.setServiceArea(serviceAreaHistories);

        //查询产业标记
        List<CompanyServiceTypeHistory> serviceTypeHistories = baseCompanyServiceTypeHistoryService.getCompanyAllServiceTypeList(checkVo.getId(), EnumDataType.After.getCode());
        checkVo.setServiceType(serviceTypeHistories);

        //查询企业资质
        List<CompanyAptitudeHistory> aptitudeHistoryList = baseCompanyAptitudeHistoryService.getCompanyAllAptitudeList(checkVo.getId(), EnumDataType.After.getCode());

        List<CompanyAptitudeHistoryMapstruct.CompanyAptitudeHistoryVo> aptitudeHistoryVos = JsonUtils.convertListObject(aptitudeHistoryList, CompanyAptitudeHistoryMapstruct.CompanyAptitudeHistoryVo.class);

        for (CompanyAptitudeHistoryMapstruct.CompanyAptitudeHistoryVo history : aptitudeHistoryVos) {
            //查询企业资质文件
            List<FileRecord> file = baseFileRecordService.getFile(history.getCompanyAptitudeId(), LocalConstant.FILE_COMPANY_APTITUDE);
            List<AppFileMapstruct.FileVo> vos = baseFileRecordService.changeFileRecordToFileVo(file);
            history.setFiles(vos);
        }
        checkVo.setCompanyAptitudeHistoryVos(aptitudeHistoryVos);

        //查询企业收益规则
//        CompanyRuleHistory histories = baseCompanyRuleHistoryService.lambdaQuery()
//                .eq(CompanyRuleHistory::getCompanyCheckId, check.getId())
//                .eq(CompanyRuleHistory::getDataType, EnumDataType.After)
//                .one();

        CompanyRuleHistoryMapstruct.CompanyRuleHistoryVo historyVos = new CompanyRuleHistoryMapstruct.CompanyRuleHistoryVo();
        List<FileRecord> file = baseFileRecordService.getFile(companyCheck.getId(), LocalConstant.FILE_COMPANY_DIVIDE_INTO_RULE);
        List<AppFileMapstruct.FileVo> vos = baseFileRecordService.changeFileRecordToFileVo(file);
        historyVos.setFiles(vos);
        checkVo.setCompanyRuleFiles(historyVos);

        return checkVo;
    }

    public ReturnPage<BusiChange> getCompanyChangeHistory(RequestPage page, CompanyChangeHistoryMapstruct.CompanyChangeHistoryVo companyChangeHistory) {
        return baseBusiChangeService.lambdaQuery().eq(BusiChange::getBusiInfoId, companyChangeHistory.getCompanyId()).orderByDesc(BusiChange::getChangeTime).page(page).getReturnPage();
    }

    public ReturnPage companyBusinessInfoPage(RequestPage page, CompanyMapstruct.PageSearchVo searchVo) {
        String isNull = "";

        //产业标记
        List<String> serviceTypeCompanyIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(searchVo.getServiceTypeName())) {
            List<CompanyServiceType> serviceTypes = baseCompanyServiceTypeService.lambdaQuery()
                    .like(StringUtils.isNotEmpty(searchVo.getServiceTypeName()), CompanyServiceType::getServiceTypeName, searchVo.getServiceTypeName())
                    .list();
            if (ListUtils.isExistsEle(serviceTypes)) {
                serviceTypeCompanyIds = serviceTypes.stream().map(CompanyServiceType::getCompanyId).collect(Collectors.toList());
            } else {
                return new ReturnPage();
            }
        }

        //项目名称
        List<String> projectNameTypeCompanyIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(searchVo.getProjectName())) {

            List<BusiInfo> infos = baseBusiInfoService.lambdaQuery().like(BusiInfo::getProjectName, searchVo.getProjectName())
                    .eq(BusiInfo::getInfoType, EnumBusinessTypeStatus.ExternalStatement)
                    .list();

            if (ListUtils.isExistsEle(infos)) {
                projectNameTypeCompanyIds = infos.stream().map(BusiInfo::getOrgId).collect(Collectors.toList());
            } else {
                return new ReturnPage();
            }
        }

        if (StringUtils.isNotEmpty(searchVo.getParentId())) {
            List<Company> childrenCompanyList = this.getAllChildrenCompanyList(searchVo.getParentId(), true);
            List<String> strings = childrenCompanyList.stream().map(Company::getCompanyId).collect(Collectors.toList());
            serviceTypeCompanyIds.addAll(strings);
        }

        RequestPage requestPage = this.lambdaQuery()
                .like(StringUtils.isNotEmpty(searchVo.getCompanyName()), Company::getCompanyName, searchVo.getCompanyName())
                .eq(StringUtils.isNotEmpty(searchVo.getParentId()), Company::getParentId, searchVo.getParentId())
                .like(StringUtils.isNotEmpty(searchVo.getParentName()), Company::getParentName, searchVo.getParentName())
                .eq(StringUtils.isNotEmpty(isNull), Company::getCompanyId, isNull)
                .in(ListUtils.isExistsEle(serviceTypeCompanyIds), Company::getCompanyId, serviceTypeCompanyIds)
                .in(ListUtils.isExistsEle(projectNameTypeCompanyIds), Company::getCompanyId, projectNameTypeCompanyIds)
                .orderByDesc(Company::getCreateDateTime)
                .page(page);

        if (ListUtils.isExistsEle(requestPage.getRecords())) {
            List<CompanyMapstruct.CompanyVo> vos = JsonUtils.convertListObject(requestPage.getRecords(), CompanyMapstruct.CompanyVo.class);
            for (CompanyMapstruct.CompanyVo vo : vos) {

                if (StringUtils.isNotEmpty(vo.getParentId()) && !"0".equals(vo.getParentId())) {
                    Company parentCompany = this.getById(vo.getParentId());
                    vo.setParentName(parentCompany.getCompanyName());
                }

                //组合产业标记
                List<CompanyServiceType> types = baseCompanyServiceTypeService.lambdaQuery().eq(CompanyServiceType::getCompanyId, vo.getCompanyId()).list();
                vo.setServiceType(types);

                //组合服务地区
                List<CompanyServiceArea> areas = baseCompanyServiceAreaService.lambdaQuery().eq(CompanyServiceArea::getCompanyId, vo.getCompanyId()).list();
                vo.setServiceArea(areas);
            }
            requestPage.setRecords(vos);
        }

        return requestPage.getReturnPage();
    }

    public List<BusiInfoMapstruct.BusiInfoVo> companyBusinessInfoChild(CompanyMapstruct.PageSearchVo searchVo) {

        if (StringUtils.isEmpty(searchVo.getCompanyId())) {
            throw CommonException.build("查询参数错误");
        }
        List<BusiInfo> companyBusiInfoList = baseBusiInfoService.lambdaQuery()
                .eq(BusiInfo::getOrgId, searchVo.getCompanyId())
                .like(StringUtils.isNotEmpty(searchVo.getProjectName()), BusiInfo::getProjectName, searchVo.getProjectName())
                .eq(BusiInfo::getInfoType, EnumBusinessTypeStatus.ExternalStatement)
                .orderByDesc(BusiInfo::getCreateDateTime)
                .list();
        List<BusiInfoMapstruct.BusiInfoVo> infoVos = JsonUtils.convertListObject(companyBusiInfoList, BusiInfoMapstruct.BusiInfoVo.class);

        if (ListUtils.isExistsEle(infoVos)) {
            for (BusiInfoMapstruct.BusiInfoVo infoVo : infoVos) {
                //组合产业标记
                List<CompanyServiceType> types = baseCompanyServiceTypeService.lambdaQuery().eq(CompanyServiceType::getCompanyId, searchVo.getCompanyId()).list();
                infoVo.setTypes(types);

                //组合服务地区
                List<CompanyServiceArea> areas = baseCompanyServiceAreaService.lambdaQuery().eq(CompanyServiceArea::getCompanyId, searchVo.getCompanyId()).list();
                infoVo.setAreas(areas);
            }
        }

        return infoVos;
    }

    public List<Company> getCompanyList(CompanyMapstruct.PageSearchVo searchVo) {
        return this.lambdaQuery().orderByDesc(Company::getCreateDateTime).eq(Company::getAuditStatus, EnumAuditStatus.Pass).list();
    }

    /**
     * 是否是新公司
     *
     * @param companyId 公司ID
     */
    public boolean isFirstNewCompany(String companyId) {
        Long count = baseCompanyCheckService.lambdaQuery()
                .eq(CompanyCheck::getCompanyId, companyId)
                .eq(CompanyCheck::getAuditStatus, EnumAuditStatus.Pass)
                .count();
        return count <= 0;
    }

    /**
     * @description: 根据产业标记以及服务地区查询公司信息
     * @author: yinzhangxiao
     * @date: 2024/11/17 16:29
     */
    public List<CompanyMapstruct.CompanyVo> getCompanyListByAreaAndServiceType(CompanyMapstruct.PageSearchVo searchVo) {
        //结果返回对象
        List<CompanyMapstruct.CompanyVo> resultList = new ArrayList<>();
        //公司查询对象
        LambdaQueryChainWrapper<Company> lq = this.lambdaQuery()
                .like(StringUtils.isNotEmpty(searchVo.getCompanyName()), Company::getCompanyName, searchVo.getCompanyName())
                .eq(Company::getStatus, EnumCompanyStatus.Normal);
        //根据服务地区查询公司id信息 服务地区城市与经营信息相同或者服务地区只选择到省份与经营信息省份相同
        if (StringUtils.isNotEmpty(searchVo.getCityCode()) && StringUtils.isNotEmpty(searchVo.getProvinceCode())) {
            List<CompanyServiceArea> areaCompanyList = baseCompanyServiceAreaService.lambdaQuery()
                    .select(CompanyServiceArea::getCompanyId)
                    .eq(CompanyServiceArea::getCityCode, searchVo.getCityCode())
                    .or(wq -> wq
                            .eq(CompanyServiceArea::getProvinceCode, searchVo.getProvinceCode())
                            .eq(CompanyServiceArea::getCityCode, StringUtils.EMPTY)
                    ).list();
            //根据地区未查询出公司信息直接返回空集合
            if (CollectionUtils.isEmpty(areaCompanyList)) {
                return resultList;
            }
            lq.in(
                    CollectionUtils.isNotEmpty(areaCompanyList),
                    Company::getCompanyId,
                    areaCompanyList.stream().map(CompanyServiceArea::getCompanyId).collect(Collectors.toList())
            );
        }
        //根据产业标记查询公司id信息
        List<CompanyServiceType> serviceTypeCompanyList = baseCompanyServiceTypeService.lambdaQuery()
                .select(CompanyServiceType::getCompanyId)
                .eq(StringUtils.isNotEmpty(searchVo.getServiceTypeId()), CompanyServiceType::getServiceTypeId, searchVo.getServiceTypeId())
                .list();
        //根据产业标记未查询出公司信息直接返回空集合
        if (StringUtils.isNotEmpty(searchVo.getServiceTypeId()) && CollectionUtils.isEmpty(serviceTypeCompanyList)) {
            return resultList;
        }
        lq.in(
                CollectionUtils.isNotEmpty(serviceTypeCompanyList),
                Company::getCompanyId,
                serviceTypeCompanyList.stream().map(CompanyServiceType::getCompanyId).collect(Collectors.toList())
        );

        resultList = CompanyMapstruct.INSTANCE.toCompanyVoList(lq.list());
        return resultList;
    }

    /**
     * 企业撤销审核
     *
     * @param companyVo
     */
    public boolean cancelCompanyCheck(CompanyMapstruct.CompanyVo companyVo) {

        if (StringUtils.isEmpty(companyVo.getCompanyId())) {
            throw CommonException.build("参数不全");
        }

        Company company = getById(companyVo.getCompanyId());
        if (company == null) {
            throw CommonException.build("企业信息不存在");
        }

        CompanyCheck check = baseCompanyCheckService.lambdaQuery()
                .eq(CompanyCheck::getCompanyId, company.getCompanyId())
                .eq(CompanyCheck::getAuditStatus, EnumAuditStatus.UnderReview)
                .eq(CompanyCheck::getCompanyUpdateType, companyVo.getCompanyUpdateType())
                .orderByDesc(CompanyCheck::getCreateDateTime).last(LocalConstant.LIMIT_1)
                .one();

        if (check == null) {
            throw CommonException.build("审核信息不存在");
        }

        baseCompanyCheckService.lambdaUpdate().eq(CompanyCheck::getId, check.getId())
                .set(CompanyCheck::getAuditStatus, EnumAuditStatus.CancelAudit)
                .update();

        baseCompanyChangeHistoryService.lambdaUpdate()
                .eq(CompanyChangeHistory::getCompanyCheckId, check.getId())
                .set(CompanyChangeHistory::getAuditStatus, EnumAuditStatus.CancelAudit)
                .update();

        company.setAuditStatus(EnumAuditStatus.CancelAudit);

        this.updateById(company);

        //发送通知事件
        Company lastNewCompanyData = this.getById(companyVo.getCompanyId());
        this.applicationContext.publishEvent(new CompanyEvent(this, lastNewCompanyData, CompanyEvent.CANCEL_COMPANY_AUDIT));

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public void delNotInformUserByCompanyId(String companyId) {
        //删除部门和权限的映射
        basePermissionMapAuthorityDepartmentService.delByCompanyId(companyId);
        //删除角色和用户的映射
        basePermissionMapRoleUserService.delByCompanyId(companyId);
        //删除角色和权限的映射
        basePermissionMapAuthorityRoleService.delByCompanyId(companyId);
        //删除权限和菜单的映射
        List<PermissionAuthority> companyAuthorityList = basePermissionAuthorityService.getAuthCompanyId(companyId);
        if (ListUtils.isExistsEle(companyAuthorityList)) {
            basePermissionMapAuthorityMenuService.delByAuthIdList(companyAuthorityList.stream().map(PermissionAuthority::getPermissionAuthorityId).collect(Collectors.toList()));
        }
        //删除角色
        basePermissionRoleService.delByCompanyId(companyId);
        //删除权限
        basePermissionAuthorityService.delByCompanyId(companyId);
        //删除权限组,删除角色组
        basePermissionGroupService.delByCompanyId(companyId);
        //删除部门员工
        baseCompanyDepartmentEmployeeService.delByCompanyId(companyId);
        //删除部门
        //删除部门员工
        baseCompanyDepartmentService.delByCompanyId(companyId);
        //删除公司员工
        baseCompanyEmployeeService.delByCompanyId(companyId);
        //------------------------ 删除审核历史和公司数据
        baseCompanyChangeHistoryService.delByCompanyId(companyId);
        baseCompanyServiceAreaHistoryService.delByCompanyId(companyId);
        baseCompanyServiceAreaService.delByCompanyId(companyId);
        baseCompanyServiceTypeHistoryService.delByCompanyId(companyId);
        baseCompanyServiceTypeService.delByCompanyId(companyId);
        baseCompanyAptitudeHistoryService.delByCompanyId(companyId);
        baseCompanyAptitudeService.delByCompanyId(companyId);

        //------------------------ 删除公司文件
        baseFileRecordService.delFile(CompanyAptitude.class, companyId);
        //删除公司
        this.removeById(companyId);
    }

//    /**
//     * 获取指定公司且公司必须在指定级别中
//     *
//     * @param companyId 公司ID
//     * @param lvList    级别
//     */
//    public Company getRedisCompanyById(String companyId, List<EnumCompanyLevel> lvList) {
//        List<Company> redisAllCompany = this.getRedisAllCompanyList();
//        if (ListUtils.isNotExistsEle(redisAllCompany)) {
//            return null;
//        }
//        List<Company> companyList = redisAllCompany.stream().filter(company -> company.getCompanyId().equals(companyId) && lvList.contains(company.getCompanyLevel())).collect(Collectors.toList());
//        if (ListUtils.isNotExistsEle(companyList)) {
//            return null;
//        }
//        return companyList.get(0);
//    }

}
